package com.siyue.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.siyue.entity.RepeatSubmit;
import com.siyue.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class RedisController {

    @Autowired
    private RedisUtil redisUtil;


    @RepeatSubmit(limitType = RepeatSubmit.Type.TOKEN)
    @PostMapping("repeatSubmit")
    public String repeatSubmit() {
        return "ok";
    }


    /**
     * 下单前获取令牌用于防重提交
     *
     * @return
     */
    @GetMapping("token")
    public String token() {
        //获取登录账户
//        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
        //随机获取32位的数字+字母作为token
        String token = getStringNumRandom(32);
        //key的组成
//        String key = String.format(RedisKey.SUBMIT_ORDER_TOKEN_KEY,accountNo,token);
        //令牌有效时间是30分钟
        redisUtil.setex(token, String.valueOf(Thread.currentThread().getId()), 30, TimeUnit.MINUTES);

        return token;
    }


    /**
     * 获取随机长度的串
     *
     * @param length
     * @return
     */
    private static final String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public String getStringNumRandom(int length) {
        //生成随机数字和字母,
        Random random = new Random();
        StringBuilder saltString = new StringBuilder(length);
        for (int i = 1; i <= length; ++i) {
            saltString.append(ALL_CHAR_NUM.charAt(random.nextInt(ALL_CHAR_NUM.length())));
        }
        return saltString.toString();
    }


}
